import {
  GetUserList,
  FreezeUserList,
  ChangeUserList,
  AddAuthorityList,
  GetAuthorityList,
  ChangeAuthorityDetail,
  RemoveAuthorityList,
  GetAuthorityPermissionById,
  UpdateRolePermission,
  GetMenuList,
  DelMenuList,
  ChangeMenuDetail,
  AddMenuList,
} from '@/services/authority_service';
import { message } from 'antd/lib/index';

// 通用算法
function toTreeData(data) {
  const resData = data;
  const tree = [];
  const treeComparison = [];
  let num = 0;
  let flag = false;
  const defaultData = [];
  const permissionIds = [];

  // runTWO(resData);
  const runTWO = function(resData) {
    treeComparison[num] = [];
    for (let i = 0; i < resData.length; i++) {
      if (resData[i].parentid === 0) {
        const key = `${'0' + '-'}${resData[i].id}`;
        if (resData[i].checked === 1) {
          defaultData.push(key);
          permissionIds.push(resData[i].id);
        }
        const obj = {
          key,
          title: resData[i].permissionname,
          children: [],
          code: resData[i].id,
        };
        tree.push(obj);
        treeComparison[0].push({ id: resData[i].id, parentid: resData[i].parentid });
        resData.splice(i, 1);
        i--;
      }

      if (flag) {
        let idp = 0;
        try {
          idp = treeComparison[num - 1].find(v => {
            return v.id === resData[i].parentid;
          }).id;
        } catch (e) {}

        let keyitem = '';
        if (idp !== 0 && resData[i].parentid === idp) {
          for (let j = num - 1; j >= 0; j--) {
            const keyid = treeComparison[j].find(v => {
              return v.id === idp;
            });
            idp = keyid.parentid;
            if (j === num - 1) {
              keyitem += keyid.id;
            } else {
              keyitem = `${keyid.id}-${keyitem}`;
            }
          }
          keyitem = `0-${keyitem}`;
          const key = `${keyitem}-${resData[i].id}`;
          if (resData[i].checked === 1) {
            defaultData.push(key);
            permissionIds.push(resData[i].id);
          }
          const obj = {
            key,
            title: resData[i].permissionname,
            children: [],
            code: resData[i].id,
            checked: resData[i].checked,
          };
          const traversal = function(tree) {
            for (let x = 0; x < tree.length; x++) {
              if (keyitem === tree[x].key) {
                tree[x].children.push(obj);
              }
              if (tree[x].children) {
                traversal(tree[x].children);
              }
            }
          };
          traversal(tree);
          treeComparison[num].push({ id: resData[i].id, parentid: resData[i].parentid });
          resData.splice(i, 1);
          i--;
        }
      }
      if (i === resData.length - 1 && resData.length !== 0) {
        flag = true;
        num++;
        runTWO(resData);
      }
    }
  };
  runTWO(resData);
  return { tree, defaultData, permissionIds };
}

export default {
  namespace: 'authority',
  state: {
    userData: {
      code: 0,
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 1,
      },
      message: '',
    },
    authorityData: {
      code: 0,
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 1,
      },
      message: '',
    },
    menuData: {
      code: 0,
      list: [],
      message: '',
    },
    treeData: { tree: [], defaultData: [], permissionIds: [] },
  },

  effects: {
    /**
     *  Created by xjc on 2019/5/21
     *  Describe:User
     */

    // 获取
    *GetUserList({ payload, callback }, { call, put }) {
      const response = yield call(GetUserList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      const result = response;
      yield put({
        type: 'saveUser',
        payload: result,
      });
      if (callback) callback(result);
    },

    // 冻结
    *FreezeUserList({ payload, callback }, { call, put }) {
      const response = yield call(FreezeUserList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 给角色
    *ChangeUserList({ payload, callback }, { call, put }) {
      const response = yield call(ChangeUserList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    /**
     *  Created by xjc on 2019/5/21
     *  Describe:Authority
     */

    // 获取
    *AddAuthorityList({ payload, callback }, { call, put }) {
      const response = yield call(AddAuthorityList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 获取
    *GetAuthorityList({ payload, callback }, { call, put }) {
      const response = yield call(GetAuthorityList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      yield put({
        type: 'saveAuthority',
        payload: response,
      });
      if (callback) callback(response);
    },

    // 修改
    *ChangeAuthorityDetail({ payload, callback }, { call, put }) {
      const response = yield call(ChangeAuthorityDetail, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 修改
    *UpdateRolePermission({ payload, callback }, { call, put }) {
      const response = yield call(UpdateRolePermission, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 删除
    *RemoveAuthorityList({ payload, callback }, { call, put }) {
      const response = yield call(RemoveAuthorityList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 树状权限id获取
    *GetAuthorityPermissionById({ payload, callback }, { call, put }) {
      const response = yield call(GetAuthorityPermissionById, payload);
      if (typeof response === 'undefined') {
        return;
      }
      console.log(response, 1111111);
      const result = toTreeData(response.list);
      yield put({
        type: 'saveAuthorityTreeData',
        payload: result,
      });
      if (callback) callback(result);
    },

    /**
     *  Created by xjc on 2019/5/22
     *  Describe:Menu
     */

    // 获取
    *GetMenuList({ payload, callback }, { call, put }) {
      const response = yield call(GetMenuList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      yield put({
        type: 'saveMenu',
        payload: response,
      });
      if (callback) callback(response);
    },

    // 删除
    *DelMenuList({ payload, callback }, { call, put }) {
      const response = yield call(DelMenuList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 修改
    *ChangeMenuDetail({ payload, callback }, { call, put }) {
      const response = yield call(ChangeMenuDetail, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },

    // 添加
    *AddMenuList({ payload, callback }, { call, put }) {
      const response = yield call(AddMenuList, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (callback) callback(response);
    },
  },

  reducers: {
    /**
     *  Created by xjc on 2019/5/21
     *  Describe:User
     */

    saveUser(state, action) {
      return {
        ...state,
        userData: action.payload === undefined ? state.userData : action.payload,
      };
    },

    /**
     *  Created by xjc on 2019/5/21
     *  Describe:Authority
     */

    saveAuthority(state, action) {
      return {
        ...state,
        authorityData: action.payload === undefined ? state.authorityData : action.payload,
      };
    },

    saveAuthorityTreeData(state, action) {
      return {
        ...state,
        treeData: action.payload === undefined ? state.treeData : action.payload,
      };
    },

    /**
     *  Created by xjc on 2019/5/22
     *  Describe:Menu
     */

    saveMenu(state, action) {
      return {
        ...state,
        menuData: action.payload === undefined ? state.menuData : action.payload,
      };
    },
  },
};
